import { Button, Card, Form, Icon, Input, Select, Radio } from 'antd';
import React, { Component } from 'react';

import { Dispatch } from 'redux';
import { FormComponentProps } from 'antd/es/form';
import { connect } from 'dva';
import { router } from 'umi';
import { formItemLayout } from '@/common/layout/form';
import { singlePageFormLayout } from '../../../../common/layout/form';
import { StoreState } from '@/common/store/store';
import { ProductAttributeCategory } from '@/models/productAttributeCategory';
import { ProductAttribute } from '../../../../models/productAttribute';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

interface FormBasicFormProps extends FormComponentProps {
  categories: ProductAttributeCategory[];
  attribute?: ProductAttribute;
  currentCategoryId?: number;
  loading?: boolean;
  dispatch: Dispatch<any>;
}

class FormBasicForm extends Component<FormBasicFormProps> {
  handleSubmit = (e: React.FormEvent) => {
    const { dispatch, form } = this.props;
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        dispatch({
          type: 'productAndFormBasicForm/submitRegularForm',
          payload: values,
        });
      }
    });
  };

  normFile = (e: { fileList: any }) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  onSubmit = () => {
    const { form, dispatch, attribute } = this.props;
    const { validateFields } = form;
    validateFields((err: any, values: any) => {
      if (!err && dispatch) {
        if (values.inputList) {
          values.inputList = values.inputList.replace(/\n/g, ',');
        }
        if (attribute) {
          dispatch({
            type: 'productAttribute/update',
            payload: {
              ...attribute,
              ...values,
            },
            callback: () => {
              router.push({
                pathname: '/product/attribute',
              });
            },
          });
        } else {
          dispatch({
            type: 'productAttribute/add',
            payload: values,
            callback: () => {
              router.push({
                pathname: '/product/attribute',
              });
            },
          });
        }
      }
    });
  };

  reset = () => {
    this.props.form.resetFields();
  };

  render() {
    const {
      form: { getFieldDecorator },
      loading,
      categories,
      attribute,
      currentCategoryId,
    } = this.props;

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const categoryOptions = categories.map(item => (
      <Option key={item.id} value={item.id}>
        {item.name}
      </Option>
    ));

    return (
      <Card
        title={
          <div>
            <Icon type="plus-square" />
            <span style={{ marginLeft: '5px' }}>添加商品属性</span>
          </div>
        }
        extra={<Button onClick={() => router.goBack()}>返回</Button>}
        style={{
          maxWidth: '750px',
          margin: 'auto',
        }}
        bordered
      >
        <Form layout="horizontal" style={singlePageFormLayout} onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label="属性名称">
            {getFieldDecorator<ProductAttribute>('name', {
              initialValue: attribute?.name,
              rules: [
                {
                  required: true,
                  message: '请输入属性名称',
                },
              ],
            })(<Input />)}
          </FormItem>
          <FormItem {...formItemLayout} label="属性分类">
            {getFieldDecorator<ProductAttribute>('productAttributeCategoryId', {
              initialValue: attribute?.productAttributeCategoryId || currentCategoryId,
            })(<Select disabled={attribute !== undefined}>{categoryOptions}</Select>)}
          </FormItem>
          <FormItem {...formItemLayout} label="属性类型">
            {getFieldDecorator<ProductAttribute>('type', {
              initialValue: attribute?.type,
            })(
              <Select disabled={attribute !== undefined}>
                <Option value={0}>规格属性</Option>
                <Option value={1}>参数属性</Option>
              </Select>,
            )}
          </FormItem>
          {/* <Form.Item {...formItemLayout} label="属性是否可选">
            {getFieldDecorator('selectType', {
              initialValue: 0,
            })(
              <Radio.Group>
                <Radio value={0}>唯一</Radio>
                <Radio value={1}>单选</Radio>
                <Radio value={2}>多选</Radio>
              </Radio.Group>,
            )}
          </Form.Item> */}
          <Form.Item {...formItemLayout} label="属性值录入方式">
            {getFieldDecorator<ProductAttribute>('inputType', {
              initialValue: attribute?.inputType || 0,
            })(
              <Radio.Group disabled={attribute !== undefined}>
                <Radio value={0}>手工录入</Radio>
                <Radio value={1}>从下面列表中选择</Radio>
              </Radio.Group>,
            )}
          </Form.Item>
          <FormItem {...formItemLayout} label="属性可选值列表">
            {getFieldDecorator<ProductAttribute>('inputList', {
              initialValue: attribute?.inputList?.replace(/,/g, '\n'),
            })(<TextArea />)}
          </FormItem>
          {/* <Form.Item {...formItemLayout} label="支持手动新增">
            {getFieldDecorator('handAddStatus', {
              initialValue: 0,
            })(
              <Radio.Group>
                <Radio value={1}>是</Radio>
                <Radio value={0}>否</Radio>
              </Radio.Group>,
            )}
          </Form.Item> */}
          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            <Button type="primary" onClick={this.onSubmit} loading={loading}>
              提交
            </Button>
            <Button onClick={this.reset} style={{ marginLeft: 8 }}>
              重置
            </Button>
          </FormItem>
        </Form>
      </Card>
    );
  }
}

const mapStateToProps = (state: StoreState) => ({
  categories: state.productAttributeCategory.categories,
  currentCategoryId: state.productAttribute.currentCategoryId,
  attribute: state.productAttribute.attribute,
  loading: state.loading.models.productAttribute,
});

export default Form.create<FormBasicFormProps>()(connect(mapStateToProps)(FormBasicForm));
